package com.zhentao.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.ChatGroupMember;
import com.zhentao.pojo.User;
import com.zhentao.service.ChatGroupMemberService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 群成员服务类
 * 提供群成员相关的业务逻辑
 */
@Service
public class GroupMemberService {

    private static final Logger log = LoggerFactory.getLogger(GroupMemberService.class);

    @Autowired
    private ChatGroupMemberService chatGroupMemberService;

    @Autowired
    private UserService usersService;

    /**
     * 根据群ID获取群成员用户名列表
     * @param groupId 群组ID
     * @return 群成员用户名列表
     */
    public List<String> getGroupMemberUsernames(Long groupId) {
        try {
            if (groupId == null) {
                log.warn("群组ID为空，无法查询群成员");
                return new ArrayList<>();
            }

            // 查询群成员
            List<ChatGroupMember> groupMembers = chatGroupMemberService.list(
                    new QueryWrapper<ChatGroupMember>().eq("group_id", groupId)
            );

            if (groupMembers.isEmpty()) {
                log.info("群组 {} 没有成员", groupId);
                return new ArrayList<>();
            }

            // 提取用户ID列表
            List<Long> userIds = groupMembers.stream()
                    .map(ChatGroupMember::getUserId)
                    .collect(Collectors.toList());

            // 查询用户信息
            List<User> users = usersService.list(
                    new QueryWrapper<User>().in("id", userIds)
            );

            // 提取用户名列表
            List<String> usernames = users.stream()
                    .map(User::getUsername)
                    .filter(username -> username != null && !username.trim().isEmpty())
                    .collect(Collectors.toList());

            log.info("群组 {} 共有 {} 个成员，获取到 {} 个有效用户名", 
                    groupId, groupMembers.size(), usernames.size());

            return usernames;

        } catch (Exception e) {
            log.error("获取群成员用户名失败: 群组ID={}", groupId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据群ID获取群成员用户ID列表
     * @param groupId 群组ID
     * @return 群成员用户ID列表
     */
    public List<Long> getGroupMemberUserIds(Long groupId) {
        try {
            if (groupId == null) {
                log.warn("群组ID为空，无法查询群成员");
                return new ArrayList<>();
            }

            // 查询群成员
            List<ChatGroupMember> groupMembers = chatGroupMemberService.list(
                    new QueryWrapper<ChatGroupMember>().eq("group_id", groupId)
            );

            // 提取用户ID列表
            List<Long> userIds = groupMembers.stream()
                    .map(ChatGroupMember::getUserId)
                    .collect(Collectors.toList());

            log.info("群组 {} 共有 {} 个成员", groupId, userIds.size());

            return userIds;

        } catch (Exception e) {
            log.error("获取群成员用户ID失败: 群组ID={}", groupId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据群ID获取群成员详细信息
     * @param groupId 群组ID
     * @return 群成员用户信息列表
     */
    public List<User> getGroupMemberUsers(Long groupId) {
        try {
            if (groupId == null) {
                log.warn("群组ID为空，无法查询群成员");
                return new ArrayList<>();
            }

            // 查询群成员
            List<ChatGroupMember> groupMembers = chatGroupMemberService.list(
                    new QueryWrapper<ChatGroupMember>().eq("group_id", groupId)
            );

            if (groupMembers.isEmpty()) {
                log.info("群组 {} 没有成员", groupId);
                return new ArrayList<>();
            }

            // 提取用户ID列表
            List<Long> userIds = groupMembers.stream()
                    .map(ChatGroupMember::getUserId)
                    .collect(Collectors.toList());

            // 查询用户信息
            List<User> users = usersService.list(
                    new QueryWrapper<User>().in("id", userIds)
            );

            log.info("群组 {} 共有 {} 个成员，获取到 {} 个用户信息", 
                    groupId, groupMembers.size(), users.size());

            return users;

        } catch (Exception e) {
            log.error("获取群成员用户信息失败: 群组ID={}", groupId, e);
            return new ArrayList<>();
        }
    }

    /**
     * 检查用户是否为群成员
     * @param groupId 群组ID
     * @param userId 用户ID
     * @return 是否为群成员
     */
    public boolean isGroupMember(Long groupId, Long userId) {
        try {
            if (groupId == null || userId == null) {
                return false;
            }

            long count = chatGroupMemberService.count(
                    new QueryWrapper<ChatGroupMember>()
                            .eq("group_id", groupId)
                            .eq("user_id", userId)
            );

            return count > 0;

        } catch (Exception e) {
            log.error("检查群成员身份失败: 群组ID={}, 用户ID={}", groupId, userId, e);
            return false;
        }
    }
}
